import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .initialization import initialize_rag_system
from .routers import rag
from .dependencies import init_rag_system

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理器
    替代即将废弃的 @app.on_event("startup")
    """
    try:
        print("正在启动服务...")
        # 启动时初始化
        rag_system = await initialize_rag_system()
        init_rag_system(rag_system)
        print("RAG系统初始化完成")
        
        yield  # 服务运行中
        
        # 关闭时清理（如果需要）
        print("正在关闭服务...")
        
    except Exception as e:
        print(f"服务生命周期管理错误: {str(e)}")
        raise

# 创建FastAPI应用，使用新的lifespan
app = FastAPI(lifespan=lifespan)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(rag.router)
